<template>
  <div class="notification-container">
    <el-dropdown class="wh-full" trigger="hover">
      <el-badge
        v-if="unreadCount > 0"
        :value="unreadCount"
       :offset="[3, -2]"
        :max="99"
      >
        <el-icon>
          <Bell />
        </el-icon>
      </el-badge>
      <el-badge v-else>
        <el-icon>
          <Bell />
        </el-icon>
      </el-badge>

      <template #dropdown>
        <div class="notification-wrapper">
          <div class="notification-header">
            <h3>我的消息</h3>
            <el-button 
              v-if="messages.length > 0" 
              type="primary" 
              link 
              @click="handleReadAll"
            >
              全部已读
            </el-button>
          </div>
          
          <div class="notification-content">
            <template v-if="messages.length > 0">
              <div class="notification-list">
                <div
                  v-for="(item, index) in messages"
                  :key="item.id || index"
                  class="message-item"
                  :class="{ 'unread': item.isRead === 0 }"
                >
                  <div class="message-header">
                    <div class="message-header-left">
                      <div class="message-content">
                        <div class="message-title-row">
                          <el-tooltip :content="item.title" placement="top" :show-after="500">
                            <div class="message-title">
                              {{ item.title }}
                            </div>
                          </el-tooltip>
                          <el-tag 
                            size="small" 
                            :type="item.isRead === 0 ? 'warning' : 'info'"
                            class="message-status"
                          >
                            {{ item.isRead === 0 ? '未读' : '已读' }}
                          </el-tag>
                        </div>
                        <el-tooltip :content="item.content" placement="top" :show-after="500">
                          <div class="message-desc">
                            {{ item.content }}
                          </div>
                        </el-tooltip>
                      </div>
                    </div>
                    <div class="message-header-right">
                      <span class="publish-time">{{ item.publishTime }}</span>
                      <div class="action-buttons">
                        <el-button
                          v-if="useNeedSettleMessage(item.type)"
                          type="primary"
                          link
                          size="small"
                          class="action-btn"
                          @click.stop="handleSettleMessage(item)"
                        >
                          去处理
                        </el-button>
                        <el-button
                          type="primary"
                          link
                          size="small"
                          class="action-btn"
                          @click.stop="handleReadMessage(item.id)"
                        >
                          我知道了
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
            <template v-else>
              <div class="empty-container">
                <el-empty :image-size="50" description="暂无消息" />
              </div>
            </template>
          </div>

          <div class="notification-footer">
            <el-link type="primary" :underline="false" @click="handleViewMore">
              <span class="footer-text">查看更多</span>
              <el-icon class="footer-icon">
                <ArrowRight />
              </el-icon>
            </el-link>
          </div>
        </div>
      </template>
    </el-dropdown>

    <NoticeDetail ref="noticeDetailRef" />
  </div>
</template>

<script setup lang="ts">
import WebSocketManager from "@/utils/websocket";
import router from "@/router";
import { type Message, MessageAPI } from "@/api/message";
import { Message2Router, useNeedSettleMessage } from "@/enums/MessageEnum";
import { onMounted, ref } from "vue";
import { ElMessage, ElNotification } from "element-plus";

// 将初始值改为 message
const activeTab = ref("message");
const messages = ref<Message[]>([]);
const noticeDetailRef = ref();
const unreadCount = ref(0);

const queryUnreadMessage = async () => {
  try {
    const res = await Promise.all([MessageAPI.queryUnread(), MessageAPI.queryUnreadCount()]);
    messages.value = res[0];
    unreadCount.value = res[1] * 1;
  } catch (error) {
    console.error("获取未读消息失败:", error);
    messages.value = [];
    unreadCount.value = 0;
  }
};

const handleSettleMessage = async (message: Message) => {
  try {
    await MessageAPI.updateIsRead(message.id);
    await queryUnreadMessage();
    router.push(Message2Router[message.type]);
  } catch (error) {
    console.error("处理消息失败:", error);
    ElMessage.error("处理消息失败，请重试");
  }
};

// 阅读消息
const handleReadMessage = async (id: number) => {
  try {
    await MessageAPI.updateIsRead(id);
    await queryUnreadMessage();
    ElMessage.success("已标记为已读");
  } catch (error) {
    console.error("标记已读失败:", error);
    ElMessage.error("标记已读失败，请重试");
  }
};

// 获取未读消息列表并连接 WebSocket
onMounted(async () => {
  await queryUnreadMessage();
  if (unreadCount.value > 0) {
    ElNotification({
      offset:50,
      title: "您有" + unreadCount.value + "条未读消息！",
      type: "warning",
      position: "top-right",
    });
  }
  WebSocketManager.subscribeToTopic("/user/queue/message", (message) => {
    try {
      const data = JSON.parse(message);
      if (data?.isMessage) {
        queryUnreadMessage();
        ElNotification({
          offset:50,
          title: "您收到一条新的消息！",
          message: data.content,
          type: "success",
          position: "top-right",
        });
      }
    } catch (error) {
      console.error("处理WebSocket消息失败:", error);
    }
  });
});

// 查看更多
function handleViewMore() {
  router.push({ path: "/myMessage" });
}

// 全部已读
const handleReadAll = async () => {
  try {
    // 如果后端有批量标记已读的接口，调用该接口
    // 否则循环调用单个标记已读
    for (const message of messages.value) {
      await MessageAPI.updateIsRead(message.id);
    }
    messages.value = [];
    unreadCount.value = 0;
    ElMessage.success("已全部标记为已读");
  } catch (error) {
    console.error("标记全部已读失败:", error);
    ElMessage.error("标记全部已读失败，请重试");
  }
};
</script>

<style lang="scss" scoped>
.wh-full {
  width: 100%;
  height: 100%;
}

:deep(.el-badge) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.notification-wrapper {
  width: 400px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.notification-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }
}

.notification-content {
  flex: 1;
  min-height: 200px;
  max-height: 400px;
}

.notification-list {
  overflow-y: auto;
  max-height: 400px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #e0e0e0;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background: #f5f5f5;
  }
}

.message-item {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s;
  cursor: pointer;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background: #fafafa;

    .action-btn {
      opacity: 1;
    }
  }

  &.unread {
    background: #f0f7ff;

    .message-title {
      font-weight: 500;
      color: #1890ff;
    }
  }
}

.message-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.message-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.message-title {
  flex: 1;
  font-size: 14px;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.message-status {
  flex-shrink: 0;
}

.message-desc {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-top: 4px;
}

.message-header-right {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 8px;
}

.publish-time {
  font-size: 12px;
  color: #999;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  padding: 0;
  font-size: 13px;
  opacity: 0;
  transition: opacity 0.3s;

  &:hover {
    color: #40a9ff;
  }
}

.empty-container {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.notification-footer {
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-text {
  font-size: 13px;
  color: #666;
}

.footer-icon {
  font-size: 13px;
  margin-left: 4px;
}

@media screen and (max-width: 768px) {
  .notification-wrapper {
    width: 100%;
    max-width: 100%;
    border-radius: 0;
  }

  .message-item {
    padding: 12px;
  }

  .action-btn {
    opacity: 1;
  }
}
.notification-container{
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>


